<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;


class Cart extends Model
{
    use HasFactory;

    protected $fillable = [
        'partition_table_record_id',
        'op_uuid',
        'product_online_id',
        'productspec_online_id',
        'qty',
        'op',
    ];

    public function saveCart($params=[]){
        $exists = $this::where('partition_table_record_id',$params['partition_table_record_id'])->exists();
        if($exists){
            throw new \Exception('桌台被占用',-110);
        }
        $op_uuid = (string)Str::orderedUuid();
        foreach ($params['detail_list'] as $item){
            $items = [
                'partition_table_record_id'=>$params['partition_table_record_id'],
                'op_uuid'=>$op_uuid,//此字段可排序
                'product_online_id'=>$item['product_online_id'],
                'productspec_online_id'=>$item['productspec_online_id'],
                'qty'=>$item['qty'],
                'op'=>'init',
            ];
            (new static())->fill($items)->save();
        }
    }

    public function editCart($params){

        $exists = $this::where('partition_table_record_id',$params['partition_table_record_id'])->exists();
        if($exists){
            $op_uuid = (string)Str::orderedUuid();
            foreach ($params['detail_list'] as $item) {
                $addItems = [
                    'partition_table_record_id' => $params['partition_table_record_id'],
                    'op_uuid'=>$op_uuid,
                    'product_online_id' => $item['product_online_id'],
                    'productspec_online_id' => $item['productspec_online_id'],
                    'qty' => $item['qty'],
                    'op'=>$item['op'],
                ];
                (new static())->fill($addItems)->save();
            }

        }else{
            throw new \Exception('开台记录不存在',-121);
        }
    }

    //购物车提交成订单后  要删除购物车，不然开新桌 不能创建购物车
    public function delCart($params){
        $this::where('partition_table_record_id',$params['partition_table_record_id'])->delete();
    }
}
